<template>
  <div class="flex space-x-5 h-full">
    <div class="bg-white rounded-content-wrap flex-shrink-0 w-[286px] p-5">
      <el-tree
        ref="tree"
        class="user-tree-wrap"
        :data="treeData"
        default-expand-all
        node-key="id"
        :expand-on-click-node="false"
        highlight-current
        @node-click="nodeClick"
      >
        <template #default="{ node, data }">
          <div class="flex justify-between w-full pr-2">
            <span>{{ data.orgName }}</span>

            <span @click.stop>
              <el-dropdown>
                <i class="el-icon-more text-gray-600"></i>
                <el-dropdown-menu slot="dropdown">
                  <a v-if="node.level === 2 || node.level === 3" @click="editDepartment(data)">
                    <el-dropdown-item>编辑</el-dropdown-item>
                  </a>
                  <a
                    v-if="node.level === 1 || node.level === 2"
                    @click="addChildDepartment(data.id)"
                  >
                    <el-dropdown-item>添加子部门</el-dropdown-item>
                  </a>
                  <!-- <a @click="setMaster(data)">
                    <el-dropdown-item>设置组织负责人</el-dropdown-item>
                  </a> -->
                  <a v-if="node.level === 2 || node.level === 3" @click="deleteDepartment(data.id)">
                    <el-dropdown-item>删除</el-dropdown-item>
                  </a>
                </el-dropdown-menu>
              </el-dropdown>
            </span>
          </div>
        </template>
      </el-tree>
    </div>
    <div
      class="
        bg-white
        rounded-content-wrap
        py-5
        text-main-title
        flex-grow flex flex-col
        overflow-hidden
        justify-between
      "
    >
      <div class="px-5">
        <div class="flex justify-between items-center">
          <div>
            <el-button type="primary" @click="addUser">添加成员</el-button>
            <!-- <el-button
              :disabled="!multipleSelection.length"
              @click="BatchSetRightVisible = true"
              >批量设置权限</el-button
            >
            <el-button
              :disabled="!multipleSelection.length"
              @click="BatchSetDepartmentVisible = true"
              >批量调整组织</el-button
            >
            <el-button
              :disabled="!multipleSelection.length"
              @click="BatchDeleteVisible = true"
              >批量删除</el-button
            > -->
          </div>

          <div>
            <el-input v-model="searchStr" placeholder="输入姓名查询" @keyup.native.enter="getList">
              <template #prefix>
                <i class="el-icon-search el-input__icon"></i>
              </template>
            </el-input>
          </div>
        </div>
        <div>
          <el-table
            v-loading="tableLoading"
            row-key="id"
            show-overflow-tooltip
            :data="tableData"
            @selection-change="handleSelectionChange"
          >
            <el-table-column reserve-selection width="50px" type="selection"></el-table-column>
            <el-table-column min-width="200px" prop="name" label="姓名">
              <template #default="{ row }">
                {{ row.accountName }}
                <!-- <el-tag size="mini" :type="row.active ? 'success' : 'danger'">{{
                  row.status === 'active' ? '已激活' : '未激活'
                }}</el-tag> -->
              </template>
            </el-table-column>
            <el-table-column min-width="150px" prop="orgName" label="部门"></el-table-column>
            <el-table-column min-width="100px" prop="role" label="用户角色">
              <template #default="{ row }">
                {{ Array.isArray(row.roleIds) ? filterRoleLabel(row.roleIds) : '' }}
              </template>
            </el-table-column>
            <el-table-column min-width="100px" prop="position" label="职位"></el-table-column>
            <el-table-column min-width="100px" prop="isWxInit" label="已关联账号">
              <template #default="{ row }">
                {{ row.isWxInit ? '是' : '否' }}
              </template>
            </el-table-column>
            <el-table-column width="100px" label="操作">
              <template #default="{ row }">
                <div class="space-x-1">
                  <a @click="editUser(row)">编辑</a> <span>|</span>
                  <a @click="deteleUser(row.id)">删除</a>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

      <div class="border-t border-solid border-gray-200 pt-5">
        <div class="flex justify-between px-5">
          <div class="flex items-center space-x-2">
            <!-- <el-checkbox>全选</el-checkbox> -->
            <div>第{{ pagination.page }}页</div>
            <div>
              当前选中 <b>{{ multipleSelection.length }}</b> 条记录
            </div>
          </div>
          <div>
            <el-pagination
              layout="total, prev, pager, next, jumper"
              :current-page.sync="pagination.page"
              :total="total"
              :page-size.sync="pagination.perPage"
              @current-change="getList"
              @size-change="getList"
            ></el-pagination>
          </div>
        </div>
      </div>
    </div>
    <AddOrUpdateUserDialog ref="AddOrUpdateUserDialog" @success="getList"></AddOrUpdateUserDialog>
    <BatchSetDepartment
      :visible.sync="BatchSetDepartmentVisible"
      :multiple-selection="multipleSelection"
    ></BatchSetDepartment>
    <BatchSetRight
      :visible.sync="BatchSetRightVisible"
      :multiple-selection="multipleSelection"
    ></BatchSetRight>
    <BatchDelete
      :visible.sync="BatchDeleteVisible"
      :multiple-selection="multipleSelection"
    ></BatchDelete>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { mapGetters } from 'vuex'
import { getUserListByOrgId, deleteUser, getUserDetail } from '@/api/user'
// this.conditions['data.name'] = { $regex: val }
// import { treeData } from './user.data'
import {
  AddOrUpdateUserDialog,
  BatchSetDepartment,
  BatchSetRight,
  BatchDelete,
} from '@/components/admin/system/user/index'
import { ActionsType as SystemActionsType } from '@/actions/system'
export default Vue.extend({
  components: {
    AddOrUpdateUserDialog,
    BatchSetDepartment,
    BatchSetRight,
    BatchDelete,
  },
  data() {
    return {
      BatchSetDepartmentVisible: false,
      BatchSetRightVisible: false,
      BatchDeleteVisible: false,

      searchStr: '',
      pagination: {
        page: 1,
        perPage: 10,
      },
      tableData: [],
      total: 0,
      multipleSelection: [],
      currentId: '',
      tableLoading: false,
    }
  },
  computed: {
    ...mapGetters('system', {
      treeData: 'departments',
      rolesEnum: 'roles',
    }),
    rolesMap() {
      return this.rolesEnum?.reduce((acc, cur) => {
        acc[cur.id] = cur.roleName
        return acc
      }, {})
    },
  },
  async mounted() {
    const res = await this.getAndBindOrgTree()
    if (res[0]) {
      this.currentId = res[0].id
      // @ts-ignore
      this.$refs.tree?.setCurrentKey(this.currentId)
    }

    this.getList()
  },
  methods: {
    filterRoleLabel(arr: string[]) {
      return arr
        .reduce((acc, cur) => {
          const hit = this.rolesMap[cur]
          if (hit) {
            acc.push(hit)
          }
          return acc
        }, [])
        .join(',')
    },
    getAndBindOrgTree() {
      return this.$store.dispatch(SystemActionsType.getDepartments)
    },
    async getList() {
      try {
        this.tableLoading = true
        const { list, pageNum, pageSize, total } = await getUserListByOrgId({
          orgId: this.currentId,
          pageNum: this.pagination.page,
          pageSize: this.pagination.perPage,
          accountName: this.searchStr,
        })
        this.tableData = list
        this.total = total
      } catch (error) {
        console.error(error)
      } finally {
        this.tableLoading = false
      }

      // console.log(res)
    },
    nodeClick(data, node, com) {
      this.currentId = data.id
      this.pagination.page = 1
      this.pagination.perPage = 10
      this.getList()
      // data.id
      console.log(data, node, com)
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    addUser() {
      // 懒惰做法
      this.$refs.AddOrUpdateUserDialog?.show()
    },
    async editUser(row) {
      const detail = await getUserDetail(row.id)
      this.$refs.AddOrUpdateUserDialog?.show(detail)
    },
    deteleUser(id) {
      this.$confirm('是否要删除此成员', '操作提示').then(async () => {
        await deleteUser(id)
        this.getList()
        this.$message.success('删除成功')
      })
    },
    editDepartment(d) {
      console.log(d)
      this.$prompt('部门名称', '编辑子部门', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: d.orgName,
      }).then(async ({ value }) => {
        await this.$store.dispatch(SystemActionsType.upsertDepartment, {
          id: d.id,
          orgName: value,
        })
        this.$message.success('编辑子部门成功!')
      })
    },
    deleteDepartment(id: string | number) {
      this.$confirm('是否要删除此部门', '操作提示').then(async () => {
        await this.$store.dispatch(SystemActionsType.deleteDepartment, id)
        this.$message.success('删除成功')
      })
    },
    addChildDepartment(id: string | number) {
      this.$prompt('部门名称', '添加子部门', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(async ({ value }) => {
        // console.log(id, value)
        await this.$store.dispatch(SystemActionsType.upsertDepartment, {
          orgName: value,
          parentId: id, // `NumberLong(${id})`,
        })

        this.$message.success('添加子部门成功!')
      })
    },
    setMaster(data: any) {
      const h = this.$createElement
      this.$prompt(
        // @ts-ignore
        h('span', [h('span', { style: 'color: red' }, '*'), h('span', undefined, '姓名 ')]),
        '设置负责人',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }
      ).then(({ value }) => {
        this.$message.success('设置负责人成功!')
      })
    },
  },
})
</script>

<style lang="scss">
.user-tree-wrap {
  .el-tree-node__content {
    // padding-top: 10px !important;
    // padding-bottom: 10px !important;
    height: 46px;
    @apply rounded-content-wrap;
  }
}
</style>
